<?php
    
    
class NJSSDK {
      public $appId;
      // # - 公众号appi ， 公众号开发配置处可查看
      private $appSecret;
      private $url;
  
  
      /**
        * @name         初始化参数
        * @author         cq <just_leaf@foxmail.com> 
        * @copyright    zydbbt 2018-10-27 
        */
      public function __construct( $appId , $appSecret,$url ) {
      
        $this    -> appId             = $appId;
        
        $this     -> appSecret         = $appSecret;
        $this     -> url                  = $url;
      }
  
  
     public function getWxConfig() {
    $jsapiTicket = $this->getJsApiTicket();
    $url = $this-> url;
    $timestamp = time();
    $nonceStr = $this->createNonceStr();
    // $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
	$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
 
    $signature = sha1($string);
 
    $signPackage = array(
      "appId"     => $this->appId,
      "nonceStr"  => $nonceStr,
      "timestamp" => $timestamp,
      "url"       => $url,
      "signature" => $signature,
      "rawString" => $string
    );
    return $signPackage; 
  }
 
  private function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }
 
  private function getJsApiTicket() {
    // $data = session('ticket');
    // if (empty($data) || $data == null) {
      $accessToken = $this->getAccessToken();
	  // file_put_contents('11.txt',$accessToken);
      $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
      $res = json_decode($this->httpGet($url));
	  
      $ticket = $res->ticket;
      if ($ticket) {
        session('ticket',$ticket);
      }
    // } else {
      // $ticket = $data;
    // }
 
    return $ticket;
  }
 
  public function getAccessToken() {
    // $data = session('accesToken');
    // if (empty($data) || $data == null) {
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
      $res = json_decode($this->httpGet($url));
      $access_token = $res->access_token;
	  // file_put_contents('22.txt',$access_token);
      if ($access_token) {
        session('accesToken',$access_token);
      }
    // } else {
      // $access_token = $data;
    // }
    return $access_token;
  }
 
  public function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_URL, $url);
 
    $res = curl_exec($curl);
    curl_close($curl);
 
    return $res;
  }
  
}